package com.hdoit.ares.web.acti.wechat;

import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.hdoit.ares.logical.acc.model.RedEnvelopeRecord;
import com.hdoit.ares.logical.acc.model.WithdrawParam;
import com.hdoit.ares.logical.acc.service.IRedEnvelopeRecordService;
import com.hdoit.ares.logical.acc.service.IWithdrawParamService;
import com.hdoit.ares.logical.acti.model.ActiReward;
import com.hdoit.ares.logical.acti.model.ActiTask;
import com.hdoit.ares.logical.acti.model.Activity;
import com.hdoit.ares.logical.acti.model.TaskGoldenBean;
import com.hdoit.ares.logical.acti.service.IActiRewardService;
import com.hdoit.ares.logical.acti.service.IActiTaskService;
import com.hdoit.ares.logical.acti.service.IActivityService;
import com.hdoit.ares.logical.acti.service.ITaskGoldenBeanService;
import com.hdoit.ares.logical.active.service.ISignService;
import com.hdoit.ares.logical.cust.model.Customer;
import com.hdoit.ares.logical.cust.service.ICustomerService;
import com.hdoit.ares.logical.official.service.IArticalCommentService;
import com.hdoit.ares.logical.policy.service.IListPolicyService;
import com.hdoit.ares.logical.share.model.ViewTime;
import com.hdoit.ares.logical.share.service.IConsultService;
import com.hdoit.ares.logical.share.service.IShareStudyService;
import com.hdoit.ares.logical.share.service.IViewTimeService;
import com.hdoit.ares.logical.viewmodel.acti.ActivitySearch;
import com.hdoit.ares.selfcommon.enums.AresManageContainer;
import com.hdoit.ares.selfcommon.enums.acc.RedEnvelopeRecordType;
import com.hdoit.ares.selfcommon.enums.acc.RedEnvelopeStatusType;
import com.hdoit.ares.selfcommon.enums.ser.GoodsCurrencyState;
import com.hdoit.ares.selfcommon.utils.DateBetween;
import com.hdoit.ares.selfcommon.utils.MathRewardUtil;
import com.tennetcn.common.enums.ModelStatus;
import com.tennetcn.common.message.PagerModel;
import com.tennetcn.common.message.WechatLoginModel;
import com.tennetcn.common.utils.CommonUtils;
import com.tennetcn.common.utils.DateUtils;
import com.tennetcn.common.utils.JsonUtils;
import com.tennetcn.component.wechat.BaseWechat;

@Controller
@RequestMapping(value = "/wechat/acti/")
public class ActivityWechat extends BaseWechat {

	@Override
	public String getRoutePath() {

		return "areas/wechat/acti/";
	}

	private IRedEnvelopeRecordService redEnvelopeRecordService;
	private IActivityService activityService;
	private IActiRewardService actiRewardService;
	private IViewTimeService viewTimeService;
	private ICustomerService customerService;
	private IWithdrawParamService withdrawParamService;
	private IActiTaskService actiTaskService;
	private ISignService signService;
	private IArticalCommentService articalCommentService;
	private IListPolicyService listPolicyService;
	private IConsultService consultService;
	private ITaskGoldenBeanService taskGoldenBeanService;
	private IShareStudyService shareStudyService;
	
	public IShareStudyService getShareStudyService() {
		return shareStudyService;
	}
	@Resource
	public void setShareStudyService(IShareStudyService shareStudyService) {
		this.shareStudyService = shareStudyService;
	}
	public ITaskGoldenBeanService getTaskGoldenBeanService() {
		return taskGoldenBeanService;
	}
	@Resource
	public void setTaskGoldenBeanService(ITaskGoldenBeanService taskGoldenBeanService) {
		this.taskGoldenBeanService = taskGoldenBeanService;
	}
	public IConsultService getConsultService() {
		return consultService;
	}
	@Resource
	public void setConsultService(IConsultService consultService) {
		this.consultService = consultService;
	}
	public IListPolicyService getListPolicyService() {
		return listPolicyService;
	}
	@Resource
	public void setListPolicyService(IListPolicyService listPolicyService) {
		this.listPolicyService = listPolicyService;
	}
	public IActiTaskService getActiTaskService() {
		return actiTaskService;
	}
	@Resource
	public void setActiTaskService(IActiTaskService actiTaskService) {
		this.actiTaskService = actiTaskService;
	}
	public ISignService getSignService() {
		return signService;
	}
	@Resource
	public void setSignService(ISignService signService) {
		this.signService = signService;
	}
	public IArticalCommentService getArticalCommentService() {
		return articalCommentService;
	}
	@Resource
	public void setArticalCommentService(IArticalCommentService articalCommentService) {
		this.articalCommentService = articalCommentService;
	}
	public IRedEnvelopeRecordService getRedEnvelopeRecordService() {
		return redEnvelopeRecordService;
	}
	@Resource
	public void setRedEnvelopeRecordService(IRedEnvelopeRecordService redEnvelopeRecordService) {
		this.redEnvelopeRecordService = redEnvelopeRecordService;
	}

	public IActivityService getActivityService() {
		return activityService;
	}
	@Resource
	public void setActivityService(IActivityService activityService) {
		this.activityService = activityService;
	}


	public IActiRewardService getActiRewardService() {
		return actiRewardService;
	}
	@Resource
	public void setActiRewardService(IActiRewardService actiRewardService) {
		this.actiRewardService = actiRewardService;
	}

	public IViewTimeService getViewTimeService() {
		return viewTimeService;
	}
	@Resource
	public void setViewTimeService(IViewTimeService viewTimeService) {
		this.viewTimeService = viewTimeService;
	}

	public ICustomerService getCustomerService() {
		return customerService;
	}
	@Resource
	public void setCustomerService(ICustomerService customerService) {
		this.customerService = customerService;
	}

	public IWithdrawParamService getWithdrawParamService() {
		return withdrawParamService;
	}
	@Resource
	public void setWithdrawParamService(IWithdrawParamService withdrawParamService) {
		this.withdrawParamService = withdrawParamService;
	}

	private final String activityViewName = "activity";
	private final String activity001ViewName = "activity001";
	private final String choujiangViewName = "choujiang";
	private final String toRewardViewName = "toReward";
	private final String hotActivityViewName ="hotActivity";
	private final String localActivityViewName ="localActivity";
	private final String activityInfoViewName ="activityInfo";
	private final String taskViewName ="task";

	@RequestMapping(value = activityViewName, method = { RequestMethod.GET, RequestMethod.POST })
	public String activity(Model model,PagerModel pagerModel,ActivitySearch search) {
		return view(activityViewName);
	}

	@RequestMapping(value = hotActivityViewName, method = { RequestMethod.GET, RequestMethod.POST })
	private String hotActivity(Model model){
		// 获取所有热门资讯
		List<Activity> hotActivitys = activityService.queryListHotActivitys();
		for (Activity hotActivity : hotActivitys) {
			Date startDate = hotActivity.getStartDate();
			Date endDate = hotActivity.getEndDate();

			String leftDate = DateBetween.leftDate(DateUtils.getCurrent(), startDate, endDate);
			if ("0".equals(leftDate)) {
				hotActivity.setDateBetween("0");
			} else {
				String[] signs = leftDate.split("_");
				String sign = signs[0];
				String date = signs[1];
				hotActivity.setSigns(sign);
				hotActivity.setDateBetween(date);
				ViewTime viewTime = viewTimeService.queryModelByShareId(hotActivity.getId(), "activity");
				hotActivity.setViewTime(viewTime);
			}
			String actiId = hotActivity.getId();
			String reward = actiRewardService.querySumReward(actiId);
			System.err.println("reward"+reward);
			String actiReward = hotActivity.getReward();
			System.err.println("actiReward"+actiReward);
			double actiRewardDouble = Double.valueOf(actiReward);
			System.err.println("actiRewardDouble"+actiRewardDouble);
			
			if (!StringUtils.isEmpty(reward)) {
				if (!StringUtils.isEmpty(actiReward)) {
					double rewardDouble = Double.valueOf(reward);
					System.err.println("rewardDouble"+rewardDouble);
					
					double leastReward = actiRewardDouble - rewardDouble - 200;
					System.err.println("leastReward"+leastReward);
					hotActivity.setLeastReward(leastReward);
				}
			} else if (StringUtils.isEmpty(reward)) {
				hotActivity.setLeastReward(actiRewardDouble);
			}
		}
		model.addAttribute("hotActivitys", hotActivitys);
		return view(hotActivityViewName);
	}
	
	@RequestMapping(value = localActivityViewName, method = { RequestMethod.GET, RequestMethod.POST })
	private String localActivity(){
		
		return view(localActivityViewName);
	}
	
	@RequestMapping(value = activityInfoViewName, method = { RequestMethod.GET, RequestMethod.POST })
	private String activityInfo(){
		
		return view(activityInfoViewName);
	}
	
	@RequestMapping(value = taskViewName, method = { RequestMethod.GET, RequestMethod.POST })
	private String task(Model model){
		List<TaskGoldenBean> taskGoldenBeans = taskGoldenBeanService.queryList();
		List<TaskGoldenBean> taskGoldenBeanList =taskGoldenBeanService.sortForArticalClassify(taskGoldenBeans);
		if(taskGoldenBeanService.applyChangeSorts(taskGoldenBeanList)){
			System.err.println("排名已更新1" + DateUtils.getCurrent());
		}
		// 获取当前登录人
		WechatLoginModel loginModel = wechatSession.getCurrentLogin();
		model.addAttribute("loginModel", loginModel);
		Customer customer = (Customer) loginModel.get(AresManageContainer.customer_account_info);
		String customerId = customer.getId();
		if("visitor".equals(customer.getLevel())){
			
		}

		// @SuppressWarnings("deprecation")
		// 如果使用了使用@Deprecated注释的方法，编译器将出现警告信息。使用这个注释将警告信息去掉。
		//@SuppressWarnings("deprecation")
		
		Calendar cal = Calendar.getInstance();
		//获取当前日期天数
		String day =String.valueOf(cal.get(Calendar.DATE));
		//获取当前日期月份
	    String month = String.valueOf(cal.get(Calendar.MONTH) + 1);
	    
	    //int year = cal.get(Calendar.YEAR);

		// 将任务所得金豆/排序字段传到前台
		TaskGoldenBean taskGoldenBean = taskGoldenBeanService.queryModelByCustomerId(customerId);
		model.addAttribute("taskGoldenBean", taskGoldenBean);
		

		// 判断当天是否签到
		boolean isDaySign = false;
		isDaySign = signService.queryIsSignedToday(month, day, customer.getId());

		// 判断当天是否评论
		boolean isDayComment = false;
		isDayComment = articalCommentService.queryCountDayComment(month, day, customerId);

		// 判断当天是否招募1名创客
		boolean isDayMakered = false;
		isDayMakered = customerService.queryIsCountDayMaker(customerId);

		// 判断当天是否分享
		boolean isDayShare = false;
		isDayShare = consultService.queryCountIsDayShare(customerId);

		// 判断每周招募3名创客
		boolean isWeekMaker = false;
		isWeekMaker = customerService.queryIsCountWeekMaker(customerId);

		// 判断每周是否学习三门课程
		boolean isWeekStudy = false;
		String studyType = "video";
		isWeekStudy = shareStudyService.queryIsCountVideos(customerId, studyType);
		
		// 判断每周下级游客是否出单1次
		boolean isWeekOrder = false;
		isWeekOrder = listPolicyService.queryCountWeekPolicy(customerId);

		// 判断每月下级游客是否出单5次
		boolean isMonthOrder = false;
		isMonthOrder = listPolicyService.queryCountMonthPolicy(customerId);

		// 判断每周是否有15天分享
		boolean isMonthShare = false;
		isMonthShare = consultService.queryCountIsMonthShare(month, customerId);

		// 判断每月是否招募到10名创客
		boolean isMonthMaker = false;
		isMonthMaker = customerService.queryIsCountMonthMaker(customerId);
		
		// 获取每日任务
		List<ActiTask> dayActiTasks = actiTaskService.queryListDayTask();
		for (ActiTask actiTasks : dayActiTasks) {
			if("sign".equals(actiTasks.getTaskId())){
				actiTasks.setTaskFinished(String.valueOf(isDaySign));
			}else if("dayComment".equals(actiTasks.getTaskId())){
				actiTasks.setTaskFinished(String.valueOf(isDayComment));
			}else if("dayMaker".equals(actiTasks.getTaskId())){
				actiTasks.setTaskFinished(String.valueOf(isDayMakered));
			}else if("dayShare".equals(actiTasks.getTaskId())){
				actiTasks.setTaskFinished(String.valueOf(isDayShare));
			}		
		}
		model.addAttribute("dayActiTasks", dayActiTasks);
		
		// 获取每周任务
		List<ActiTask> weekActiTasks = actiTaskService.queryListWeekTask();
		for (ActiTask actiTasks : weekActiTasks) {
			if("weekVistorOrder".equals(actiTasks.getTaskId())){
				actiTasks.setTaskFinished(String.valueOf(isWeekOrder));
			}else if("weekMaker".equals(actiTasks.getTaskId())){
				actiTasks.setTaskFinished(String.valueOf(isWeekMaker));
			}else if("weekStudy".equals(actiTasks.getTaskId())){
				actiTasks.setTaskFinished(String.valueOf(isWeekStudy));
			}
		}
		model.addAttribute("weekActiTasks", weekActiTasks);
		
		// 获取每月任务
		List<ActiTask> monthActiTasks = actiTaskService.queryListMonthTask();
		for (ActiTask actiTasks : monthActiTasks) {
			if("monthMaker".equals(actiTasks.getTaskId())){
				actiTasks.setTaskFinished(String.valueOf(isMonthMaker));
			}else if("monthVisitorOrder".equals(actiTasks.getTaskId())){
				actiTasks.setTaskFinished(String.valueOf(isMonthOrder));
			}else if("monthShare".equals(actiTasks.getTaskId())){
				actiTasks.setTaskFinished(String.valueOf(isMonthShare));
			}
		}
		model.addAttribute("monthActiTasks", monthActiTasks);
		
		return view(taskViewName);
	}
	// 活动界面001
	@RequestMapping(value = activity001ViewName, method = { RequestMethod.GET, RequestMethod.POST })
	public String activity001(Model model, String id) {

		// 更新参加活动次数
		viewTimeService.updateViewTimeById(id, "activity");

		// 查询当前活动详情
		Activity activity = activityService.queryModel(id);

		// 判断当前活动的状态
		Date startDate = activity.getStartDate();
		Date endDate = activity.getEndDate();
		String leftDate = DateBetween.leftDate(DateUtils.getCurrent(), startDate, endDate);
		if ("0".equals(leftDate)) {
			activity.setDateBetween("0");
		} else {
			String[] signs = leftDate.split("_");
			String sign = signs[0];
			String date = signs[1];
			activity.setSigns(sign);
			activity.setDateBetween(date);
		}
		model.addAttribute("activity", activity);

		// 查询当前活动参与次数
		ViewTime viewTime = viewTimeService.queryModelByShareId(activity.getId(), "activity");
		model.addAttribute("viewTime", viewTime);

		// 查询当前活动的中奖名单
		List<ActiReward> actiRewards = actiRewardService.queryList(id);
		model.addAttribute("actiRewards", actiRewards);

		// 查询当前用户的等级
		WechatLoginModel loginModel = wechatSession.getCurrentLogin();
		Customer customer = (Customer) loginModel.get(AresManageContainer.customer_account_info);
		String level = customer.getLevel();
		model.addAttribute("level", level);

		// 判断当前用户加入初创的时间
		Date joinMarkDate = customer.getJoinMakerDate();
		String joinDate = DateUtils.dateFormat(joinMarkDate);

		if (!StringUtils.isEmpty(joinDate)) {
			String joinDateBetween = DateBetween.dateBetween(joinMarkDate, startDate, endDate);
			model.addAttribute("joinDateBetween", joinDateBetween);
		}
		return view(activity001ViewName);
	}

	// 抽奖界面
	@RequestMapping(value = choujiangViewName, method = { RequestMethod.GET, RequestMethod.POST })
	public String choujiang(Model model, String actiId) {

		WechatLoginModel loginModel = wechatSession.getCurrentLogin();
		Customer customer = (Customer) loginModel.get(AresManageContainer.customer_account_info);
		String customerId = customer.getId();

		ActiReward actiReward = actiRewardService.queryModelByCustId(customerId);
		Integer mathRewardUtil = MathRewardUtil.main();
		if (!StringUtils.isEmpty(actiReward)) {
			System.err.println("actiReward not empty");
			mathRewardUtil = 0;
			System.err.println("actiReward is  empty");
			return activity001(model, actiId);
		}
		model.addAttribute("mathRewardUtil", mathRewardUtil);

		Activity activity = activityService.queryModel(actiId);
		Date startDate = activity.getStartDate();
		Date endDate = activity.getEndDate();

		Date joinMakerDate = customer.getJoinMakerDate();
		if (joinMakerDate != null) {
			System.err.println("joinMakerDate ！= null");
			String makerDate = DateBetween.dateBetween(joinMakerDate, startDate, endDate);
			if (!"between".equals(makerDate) || ("between".equals(makerDate) && !StringUtils.isEmpty(actiReward))) {
				System.err.println("between ！= makerDate");
				return activity001(model, actiId);
			}
		} else {
			System.err.println("joinMakerDate == null");
			return activity001(model, actiId);
		}
		Date joinHighMakerDate = customer.getJoinHighMakerDate();
		if (joinHighMakerDate != null) {
			System.err.println("joinHighMakerDate == null");
			String highMakerDate = DateBetween.dateBetween(joinHighMakerDate, startDate, endDate);
			if (!"between".equals(highMakerDate) || ("between".equals(highMakerDate) && !StringUtils.isEmpty(actiReward))) {
				System.err.println("between == highMakerDate");
				return activity001(model, actiId);
			}
		}
		model.addAttribute("actiId", actiId);

		// 将获奖名单传到前台
		List<ActiReward> actiRewards = actiRewardService.queryList();
		model.addAttribute("actiRewards", actiRewards);

		return view(choujiangViewName);
	}

	// 向奖金数据记录
	@ResponseBody
	@RequestMapping(value = toRewardViewName, method = { RequestMethod.GET, RequestMethod.POST })
	public String toReward(Model model, String actiId) {

		System.err.println("toReward actiId" + actiId);
		// 查询是否抽过奖
		WechatLoginModel loginModel = wechatSession.getCurrentLogin();
		model.addAttribute("loginModel", loginModel);
		Customer customer = (Customer) loginModel.get(AresManageContainer.customer_account_info);

		String customerId = customer.getId();
		System.err.println("customerId" + customerId);
		String id = "empty";
		ActiReward actiReward = actiRewardService.queryModelByCustId(customerId);
		Integer mathRewardUtil1 = MathRewardUtil.main();
		if (!StringUtils.isEmpty(actiReward)) {
			mathRewardUtil1 = 0;
		} else {
			actiReward = new ActiReward();
			actiReward.setId(CommonUtils.getKeyId());
			actiReward.setActiId(actiId);
			actiReward.setCustomerId(customer.getId());
			actiReward.setRewardDate(DateUtils.getCurrent());
			String userName = customer.getUsername();
			if (!StringUtils.isEmpty(userName)) {
				actiReward.setUserName(userName);
			} else {
				throw new RuntimeException("error:someOne filing reward");
			}
			actiReward.setRewardCurrency(GoodsCurrencyState.yuan);

			if (mathRewardUtil1 == 1) {
				WithdrawParam withdrawParam = withdrawParamService.queryModelByHelpCode("thirdReward");
				actiReward.setReward(String.valueOf(withdrawParam.getParam()));
			} else if (mathRewardUtil1 == 3) {
				WithdrawParam withdrawParam = withdrawParamService.queryModelByHelpCode("firstReward");
				actiReward.setReward(String.valueOf(withdrawParam.getParam()));
			} else if (mathRewardUtil1 == 6) {
				WithdrawParam withdrawParam = withdrawParamService.queryModelByHelpCode("secondReward");
				actiReward.setReward(String.valueOf(withdrawParam.getParam()));
			} else {
				return activity001(model, id);
			}

			actiReward.setDeleteMark("1");
			actiReward.setModelStatus(ModelStatus.add);
			if (!actiRewardService.applyChange(actiReward)) {

				throw new RuntimeException("actiReward save error");
			}

			RedEnvelopeRecord redEnvelopeRecord = new RedEnvelopeRecord();
			String redEnvelopeRecordId = CommonUtils.getKeyId();
			redEnvelopeRecord.setId(redEnvelopeRecordId);
			redEnvelopeRecord.setReceiverId(customerId);
			String refereeId = customer.getRefereeId();
			if (!StringUtils.isEmpty(refereeId)) {
				redEnvelopeRecord.setRefreeId(refereeId);
				Customer refreeCustomer = customerService.queryModel(refereeId);
				redEnvelopeRecord.setRefreeLevel(refreeCustomer.getLevel());
			}

			redEnvelopeRecord.setJoinId(customer.getId());
			redEnvelopeRecord.setJoinLevel(customer.getLevel());
			redEnvelopeRecord.setRedMoney(Double.valueOf(actiReward.getReward()));
			redEnvelopeRecord.setSendDate(DateUtils.getCurrent());
			redEnvelopeRecord.setCategory(RedEnvelopeRecordType.joinByrefreeCustomer);
			redEnvelopeRecord.setRedenvelopeStatus(RedEnvelopeStatusType.notReceived);
			redEnvelopeRecord.setTradeNo("");
			redEnvelopeRecord.setDuration(RedEnvelopeStatusType.duration);
			redEnvelopeRecord.setModelStatus(ModelStatus.add);

			// 如果红包记录添加成功
			if (redEnvelopeRecordService.applyChange(redEnvelopeRecord)) {
				id = redEnvelopeRecordId;
			}
		}
		String mathRewardUtil = String.valueOf(mathRewardUtil1);
		System.err.println("mathRewardUtil" + mathRewardUtil);
		System.err.println("id" + id);
		HashMap<String, Object> res = new HashMap<String, Object>();
		res.put("id", id);
		res.put("mathRewardUtil", mathRewardUtil);

		System.err.println("sadasdsa==========" + JsonUtils.toJson(res));
		return JsonUtils.toJson(res);
	}
	

}
